package com.topboya.officeuser.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.topboya.common.service.CrudService;
import com.topboya.common.utils.DateUtils;
import com.topboya.common.utils.FileUtils;
import com.topboya.common.utils.JedisUtils;
import com.topboya.common.utils.excel.ImportExcel;
import com.topboya.modules.exam.bank.entity.BoyaQFile;
import com.topboya.modules.exam.bank.service.BoyaQFileService;
import com.topboya.modules.salesClosing.entity.BoyaSalesInfo;
import com.topboya.modules.salesClosing.listener.BoyaSalesInfoListener;
import com.topboya.modules.salesClosing.listener.ExcelReaderUtil;
import com.topboya.modules.salesClosing.mapper.BoyaSalesInfoMapper;
import com.topboya.modules.sys.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * (BoyaSalesInfo)表服务接口
 *
 * @author makejava
 * @since 2020-11-11 15:17:04
 */
@Service
@Transactional(readOnly = false)
public class BoyaSalesInfoService extends CrudService<BoyaSalesInfoMapper, BoyaSalesInfo> {

    @Autowired
    BoyaQFileService boyaQFileService;

    BoyaQFile boyaQFile;


    @Transactional
    public BoyaQFile importBoyaSaleInfor(FileUtils.FileInfo file, User user,ImportExcel importExcel) throws IOException {
        int successNum = 0;
        int failNum = 0;//失败行数
        BoyaSalesInfo salesInfor = new BoyaSalesInfo();

        salesInfor.setCurrentUser(user);
        int fileLine = importExcel.realExcelDataNum(importExcel, 1, 25);
        List<BoyaSalesInfo> salesInforList = new LinkedList<>();
        int rowNum = importExcel.getLastDataRowNum();
        int max = rowNum - 1;
        BoyaQFile qFile = boyaQFileService.saveQFile(importExcel, file, fileLine, user, 9);
        String fileId = qFile.getId();
        dao.clearAllBoyaSaleInfo();
        successNum = MakeSalesInfo(user, importExcel, salesInforList, rowNum, max, fileId,file,successNum);

        insertSalesInforBatch(salesInforList);
        successNum += salesInforList.size();
        salesInforList.clear();

        JedisUtils.set("remainNum_" + fileId, "0", 1800);

        FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath());
        importExcel.getWb().write(fileOutputStream);
        qFile.setImpSuccessLine(successNum);
        qFile.setImpFailLine(failNum);
        qFile.setSuccess(1);
        boyaQFileService.save(qFile);
        return qFile;
    }

    /**
     * 读取excel，保存到List集合
     * @param user
     * @param importExcel
     * @param salesInforList
     * @param rowNum
     * @param max
     * @param fileId
     * @param file
     * @param successNum
     */
    private int MakeSalesInfo(User user, ImportExcel importExcel, List<BoyaSalesInfo> salesInforList, int rowNum, int max, String fileId, FileUtils.FileInfo file, int successNum) {

        JedisUtils.set("maxExcelNum_" + fileId, String.valueOf(max), 1800);
        JedisUtils.set("remainNum_" + fileId, String.valueOf(max), 1800);
        BoyaSalesInfo n_boyaSalesInfo;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date r_date = new Date();
        for (int i = 1; i <= rowNum; i++) {
            n_boyaSalesInfo = new BoyaSalesInfo();
            Row row = importExcel.getRow(i);

            String id = importExcel.getCellValue(row, 0).toString().trim();//ID
            String remarks = importExcel.getCellValue(row, 1).toString().trim();//备注
            String uploadYear = importExcel.getCellValue(row, 2).toString().trim();//上传年
            String uploadMonth = importExcel.getCellValue(row, 3).toString().trim();//上传月
            String productName = importExcel.getCellValue(row, 4).toString().trim();//产品名称
            String productUnit = importExcel.getCellValue(row, 5).toString().trim();//产品规格
            String productFactory = importExcel.getCellValue(row, 6).toString().trim();//生产厂家
            String supplyPrice = importExcel.getCellValue(row, 7).toString().trim();//供货价
            String salesAmount = importExcel.getCellValue(row,8).toString().trim();//销售金额

            String inComeDate = importExcel.formatExcelTime(df, file.getFile().getName(), row, 9);//进药日期
            String salesCount = importExcel.getCellValue(row, 10).toString().trim();//进药量
            String business = importExcel.getCellValue(row, 11).toString().trim();//商业
            String orgCode = importExcel.getCellValue(row, 12).toString().trim();//医院编码
            String orgName = importExcel.getCellValue(row, 13).toString().trim();//医院名称
            String orgLevel = importExcel.getCellValue(row, 14).toString().trim();//级别
            String orgCategory = importExcel.getCellValue(row, 15).toString().trim();//医院分类
            String extraOrgName = importExcel.getCellValue(row,16).toString().trim();//外部医院名称
            String orgArea = importExcel.getCellValue(row, 17).toString().trim();//城区
            String userName = importExcel.getCellValue(row,18).toString().trim();//代表
            String developer = importExcel.getCellValue(row,19).toString().trim();//开发者
            String userBelong = importExcel.getCellValue(row, 20).toString().trim();//代表归属
            String superiorName = importExcel.getCellValue(row, 21).toString().trim();//公司主管
            String distributionGroup = importExcel.getCellValue(row, 22).toString().trim();//分销组
            String distributionLeader = importExcel.getCellValue(row, 23).toString().trim();//分销经理
            String place = importExcel.getCellValue(row, 24).toString().trim();//地方社区
            String lotNumber = importExcel.getCellValue(row, 25).toString().trim();//批号
            LocalDate shipDate = LocalDate.of(Integer.parseInt(uploadYear), Integer.parseInt(uploadMonth), 1);
            n_boyaSalesInfo.setUploadYear(Integer.parseInt(uploadYear));
            n_boyaSalesInfo.setUploadMonth(Integer.parseInt(uploadMonth));
            n_boyaSalesInfo.setProductName(productName);
            n_boyaSalesInfo.setProductUnit(productUnit);
            n_boyaSalesInfo.setProductFactory(productFactory);
            n_boyaSalesInfo.setSupplyPrice(supplyPrice);
            n_boyaSalesInfo.setShipDate(shipDate.toString());
            try {
                Date date = DateUtils.parseDate(inComeDate, "yyyy-MM-dd");
                n_boyaSalesInfo.setInComeDate(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            n_boyaSalesInfo.setSalesAmount(Float.parseFloat(salesAmount));
            n_boyaSalesInfo.setSalesCount(Double.parseDouble(salesCount));
            n_boyaSalesInfo.setBusiness(business);
            n_boyaSalesInfo.setOrgCode(orgCode);
            n_boyaSalesInfo.setOrgName(orgName);
            n_boyaSalesInfo.setOrgLevel(orgLevel);
            n_boyaSalesInfo.setOrgCategory(orgCategory);
            n_boyaSalesInfo.setExtraOrgName(extraOrgName);
            n_boyaSalesInfo.setOrgArea(orgArea);
            n_boyaSalesInfo.setDeveloper(developer);
            n_boyaSalesInfo.setUserName(userName);
            n_boyaSalesInfo.setUserBelong(userBelong);
            n_boyaSalesInfo.setSuperiorName(superiorName);
            n_boyaSalesInfo.setDistributionGroup(distributionGroup);
            n_boyaSalesInfo.setDistributionLeader(distributionLeader);
            n_boyaSalesInfo.setPlace(place);
            n_boyaSalesInfo.setLotNumber(lotNumber);
            n_boyaSalesInfo.setRemarks(remarks);
            n_boyaSalesInfo.setCreateBy(user);
            n_boyaSalesInfo.setCreateDate(r_date);
            n_boyaSalesInfo.setUpdateBy(user);
            n_boyaSalesInfo.setUpdateDate(r_date);
            n_boyaSalesInfo.setDelFlag("0");
            n_boyaSalesInfo.setId(id);
            n_boyaSalesInfo.setCurrentUser(user);
            salesInforList.add(n_boyaSalesInfo);

            if(salesInforList.size()>1000) {
                insertSalesInforBatch(salesInforList);
                successNum += salesInforList.size();
                salesInforList.clear();
            }
            max = --max;
            JedisUtils.set("remainNum_" + fileId, String.valueOf(max), 1800);
        }
        return successNum;
    }

    /**
     * 将list集合中的元素插入数据
     * @param salesInforList
     */
    @Transactional(readOnly = false)
    public void insertSalesInforBatch(List<BoyaSalesInfo> salesInforList) {
            //批量添加
        dao.insertSalesInforBatch(salesInforList);
    }

    @Transactional(readOnly = false)
    public void updateSubmitFlag(BoyaSalesInfo boyaSalesInfo) {
       dao.updateSubmitFlag(boyaSalesInfo);
    }

    @Transactional
    public void clearAllBoyaSaleInfor() {
        dao.clearAllBoyaSaleInfo();
    }

    public BoyaQFile importBoyaSaleInforForEs(FileUtils.FileInfo file, User user) throws IOException {

        File fileFile = file.getFile();
//        String fileName = "C:\\Users\\boya\\Desktop\\公司项目\\未结费用明细.xlsx";
//        InputStream in;
        File files = null;
//        in = new FileInputStream(fileName);
        FileInputStream in = new FileInputStream(fileFile);

        ExcelReaderBuilder readWorkBook = EasyExcel.read(in, BoyaSalesInfo.class, new BoyaSalesInfoListener(user,file));
        readWorkBook.sheet().doRead();
        return boyaQFile;
    }


    public void getQFileForIndex(BoyaQFile qFile) {
        this.boyaQFile = qFile;
    }

    public BoyaQFile importBoyaSaleInforForSax(FileUtils.FileInfo file, User user) throws Exception {
        int successNum = 0;
        int failNum = 0;//失败行数
        BoyaSalesInfo salesInfor = new BoyaSalesInfo();
        List<List<String>> dataList = ExcelReaderUtil.readExcel(file.getAbsolutePath());   
        int fileLine = dataList.size()-3;
 
        salesInfor.setCurrentUser(user);
        List<BoyaSalesInfo> salesInforList = new LinkedList<>();

        Date r_date = new Date();

        for (int i = 0; i < dataList.size(); i++) {
            List<String> cellList = dataList.get(i);
            if(i==0){
                continue;
            }
            if(StringUtils.isBlank(cellList.get(0).trim())){
                cellList.add("id为必填项");
            } else{
                String id  =              cellList.get(0).trim();
                String remarks =          cellList.get(1).trim();
                String uploadYear =       cellList.get(2).trim();
                String uploadMonth =      cellList.get(3).trim();
                String productName =      cellList.get(4).trim();
                String productUnit =        cellList.get(5).trim();
                String productFactory =   cellList.get(6).trim();
                String supplyPrice =      cellList.get(7).trim();
                String salesAmount =       cellList.get(8).trim();
                String inComeDate =        cellList.get(9).trim();
                String salesCount =        cellList.get(10).trim();
                String business =          cellList.get(11).trim();
                String orgCode =           cellList.get(12).trim();
                String orgName =           cellList.get(13).trim();
                String orgLevel =          cellList.get(14).trim();
                String orgCategory =        cellList.get(15).trim();
                String extraOrgName =       cellList.get(16).trim();
                String orgArea =            cellList.get(17).trim();
                String userName =           cellList.get(18).trim();
                String developer =          cellList.get(19).trim();
                String userBelong =         cellList.get(20).trim();
                String superiorName =       cellList.get(21).trim();
                String distributionGroup =  cellList.get(22).trim();
                String distributionLeader =  cellList.get(23).trim();
                String place =                cellList.get(24).trim();
                String lotNumber =             cellList.get(25).trim();
                BoyaSalesInfo n_boyaSalesInfo = new BoyaSalesInfo();
                LocalDate shipDate = LocalDate.of(Integer.parseInt(uploadYear), Integer.parseInt(uploadMonth), 1);
                n_boyaSalesInfo.setUploadYear(Integer.parseInt(uploadYear));
                n_boyaSalesInfo.setUploadMonth(Integer.parseInt(uploadMonth));
                n_boyaSalesInfo.setProductName(productName);
                n_boyaSalesInfo.setProductUnit(productUnit);
                n_boyaSalesInfo.setProductFactory(productFactory);
                n_boyaSalesInfo.setSupplyPrice(supplyPrice);
                n_boyaSalesInfo.setShipDate(shipDate.toString());
                try {
                    Date date = DateUtils.parseDate(inComeDate, "yyyy-MM-dd");
                    n_boyaSalesInfo.setInComeDate(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                n_boyaSalesInfo.setSalesAmount(Float.parseFloat(salesAmount));
                n_boyaSalesInfo.setSalesCount(Double.parseDouble(salesCount));
                n_boyaSalesInfo.setBusiness(business);
                n_boyaSalesInfo.setOrgCode(orgCode);
                n_boyaSalesInfo.setOrgName(orgName);
                n_boyaSalesInfo.setOrgLevel(orgLevel);
                n_boyaSalesInfo.setOrgCategory(orgCategory);
                n_boyaSalesInfo.setExtraOrgName(extraOrgName);
                n_boyaSalesInfo.setOrgArea(orgArea);
                n_boyaSalesInfo.setDeveloper(developer);
                n_boyaSalesInfo.setUserName(userName);
                n_boyaSalesInfo.setUserBelong(userBelong);
                n_boyaSalesInfo.setSuperiorName(superiorName);
                n_boyaSalesInfo.setDistributionGroup(distributionGroup);
                n_boyaSalesInfo.setDistributionLeader(distributionLeader);
                n_boyaSalesInfo.setPlace(place);
                n_boyaSalesInfo.setLotNumber(lotNumber);
                n_boyaSalesInfo.setRemarks(remarks);
                n_boyaSalesInfo.setCreateBy(user);
                n_boyaSalesInfo.setCreateDate(r_date);
                n_boyaSalesInfo.setUpdateBy(user);
                n_boyaSalesInfo.setUpdateDate(r_date);
                n_boyaSalesInfo.setDelFlag("0");
                n_boyaSalesInfo.setId(id);
                n_boyaSalesInfo.setCurrentUser(user);
                salesInforList.add(n_boyaSalesInfo);

                if(salesInforList.size()>1000) {
                    insertSalesInforBatch(salesInforList);
                    successNum += salesInforList.size();
                    salesInforList.clear();
                }
            }
        }
    }
}